package com.barradata.app0624.modules.login

import android.content.Context
import android.content.Intent
import android.view.View
import com.barradata.BuildConfig
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.app0624.data.UserDataManager
import com.barradata.app0624.modules.web.EventType
import com.barradata.app0624.modules.web.WebCallbackEvent
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.barradata.common.utils.ToastUtils
import com.example.hfiveandaplication.bean.LoginData
import com.facebook.accountkit.AccountKitLoginResult
import com.facebook.accountkit.ui.AccountKitActivity
import com.facebook.accountkit.ui.AccountKitConfiguration
import com.facebook.accountkit.ui.LoginType
import com.facebook.accountkit.ui.ThemeUIManager
import com.google.gson.Gson
import kotlinx.android.synthetic.main.login_activity.*


/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/15 10:56
 * Description: 登录页面
 **/
class LoginActivity : BaseActivity() {
    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }

        private const val APP_REQUEST_CODE = 99
    }

    override fun getLayoutId() = R.layout.login_activity

    override fun initView() {
        tv_login_by_facebook.clickV().subscribe {
            facebook_login()
        }.autoClean()
        tv_login.visibility = if (BuildConfig.DEBUG) View.VISIBLE else View.GONE
        tv_login.clickV().subscribe {
            DebugLoginActivity.actionStart(this)
            finish()
        }.autoClean()

    }

    private fun facebook_login() {
        val whitelist = arrayOf("ID")
        val intent = Intent(this, AccountKitActivity::class.java)
        val configurationBuilder = AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
                AccountKitActivity.ResponseType.CODE)
                .setDefaultCountryCode("ID").setSMSWhitelist(whitelist)
        configurationBuilder.setUIManager(ThemeUIManager(R.style.AppLoginTheme))
        // ... perform additional configuration ...
        intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configurationBuilder.build())
        startActivityForResult(intent, APP_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == APP_REQUEST_CODE) {
            try {
                val loginResult = data?.getParcelableExtra<AccountKitLoginResult>(AccountKitLoginResult
                        .RESULT_KEY)!!
                val toastMessage: String
                if (loginResult.error != null) {
                    toastMessage = loginResult.error?.errorType?.message!!
                } else if (loginResult.wasCancelled()) {
                    toastMessage = "Login Cancelled"
                } else {
                    toastMessage = "Success"
                    ApiService.facebookLogin(loginResult.authorizationCode!!)
                            .doOnSubscribe { showLoadingView() }
                            .doFinally { dismissLoadingView() }
                            .subscribe({
                                if (it.isRel) {
                                    try {
                                        if (it.data.token.isEmpty()) {
                                            ToastUtils.showShort(R.string.token_is_null)
                                            return@subscribe
                                        }
                                        UserDataManager.token = it.data.token
                                        requestUserStatus()
                                    } catch (exception: java.lang.Exception) {
                                        ToastUtils.showShort(it.message)
                                    }
                                } else {
                                    ToastUtils.showShort(it.message)
                                }
                            }, {
                                it.printStackTrace()
                                logE(it.message.toString())
                            }).autoClean()
                }
                ToastUtils.showShort(toastMessage)
            } catch (e: Exception) {
                e.printStackTrace()
                logD(e.toString())
            }

        }
    }

    private fun requestUserStatus() {
        ApiService.getStatus().subscribe({
            UserDataManager.uuid = it.data.userUuid
            UserDataManager.addressBookUuid = it.data.addressBookUuid
            if (UserDataManager.token.isEmpty()) {
                ToastUtils.showShort(R.string.token_is_null)
                return@subscribe
            }
            ToastUtils.showShort(R.string.login_page_login_success)
            RxBus.post(WebCallbackEvent(EventType.FROM_LOGIN))
            finish()
        }, {
            ToastUtils.showShort(it.message.toString())
        }).autoClean()
    }

}